package com.alog.common.code;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class LockConsumer extends Thread {
    private Lock lock;
    private Condition condition;

    public LockConsumer(Lock lock, Condition condition,String threadName){
        super(threadName);
        this.lock = lock;
        this.condition = condition;
    }

    @Override
    public void run() {
        while (true){
            lock.lock();
            if(Queue.getInstance().size() <= 0){
                try {
                    condition.await();
                    continue;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            String content = Queue.getInstance().poll();
            System.out.println(Thread.currentThread().getName() + " poll " + content);
            condition.signalAll();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.unlock();
        }
    }
}
